package com.springclouddemo.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String, Date> {
    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
    private static final String dateFormat1 = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";
    private static final String shortDateFormat2 = "yyyy/MM/dd";
    private static final String timeStampFormat = "^\\d+$";
    @Override
    public Date convert(String dateString) {
        if(StringUtils.isBlank(dateString)) {
            return null;
        }
        dateString = dateString.trim();
        try {
            if (dateString.contains("-")) {
                SimpleDateFormat formatter;
                if (dateString.contains(":")) {
                    formatter = new SimpleDateFormat(dateFormat);//yyyy-MM-dd HH:mm:ss
                } else {
                    formatter = new SimpleDateFormat(shortDateFormat);//yyyy-MM-dd
                }
                return formatter.parse(dateString);
            } else if (dateString.matches(timeStampFormat)) {
                Long lDate = new Long(dateString);//tickets
                return new Date(lDate);
            }else if (dateString.contains("/")){
                SimpleDateFormat formatter;
                if (dateString.contains(":")) {
                    formatter = new SimpleDateFormat(dateFormat1);//yyyy/MM/dd HH:mm:ss
                } else {
                    formatter = new SimpleDateFormat(shortDateFormat2);//yyyy/MM/dd
                }
                return formatter.parse(dateString);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parse %s to Date failed", dateString));
        }
        throw new RuntimeException(String.format("parse %s to Date failed", dateString));
    }
}